package chpt08;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;

public class BufferedFileTest {	
	public static void main(String[] args) throws IOException{
		Person[] persons= new Person[3];
		persons[0]=new Person(1,"张三","12345");
		persons[1]=new Person(2,"李四","67890");
		persons[2]=new Person(3,"王五","12389");
		try(BufferedWriter bw = new BufferedWriter(new FileWriter("person.csv",Charset.forName("UTF-8")))){
			for(Person p:persons)
				writePerson(bw,p);
		}
		try(BufferedReader br = new BufferedReader(new FileReader("person.csv",Charset.forName("UTF-8")))){
			String line = null;
			Person p;
			while( (line= br.readLine())!=null) {
				p = resolvePerson(line);
				System.out.println(p);
			}
		}		
	}
	private static void writePerson(BufferedWriter writer,Person p) throws IOException{
		writer.write(p.getId()+":"+p.getName()+":"+p.getTel());
		writer.newLine();
	}
	private static Person resolvePerson(String line) {
		String[] tokens = line.split(":");
		int id = Integer.parseInt(tokens[0]);
		return new Person(id,tokens[1],tokens[2]);
	}	
}
